package main

import (
	"fmt"
	"github.com/braintree/manners"
	"github.com/gin-gonic/gin"
	"github.com/tidwall/gjson"
	"net/http"
	"nextFlow/flow"
	_ "nextFlow/native_modules"
	"nextFlow/node"
	"nextFlow/types"
	"nextFlow/utils"
)

func main() {

	/*myflow := flow.New()

	jsonByte, _ := utils.ReadFile("task1.json", "tasks")

	data := types.H{"@this": string(jsonByte)}

	data.Get("nodes").ForEach(func(key, value gjson.Result) bool {
		myflow.AddNode(node.New(types.H{"@this": value.String()}))
		return true
	})

	myflow.Debug(func(v ...interface{}) {
		fmt.Println(v...)
	}).Trigger(func(v ...interface{}) {
		fmt.Println(v...)
	}).(*flow.FlowStruct).Start(types.H{"k": "d"}).End(func() {
		fmt.Println("结束")
	})

	return*/

	router := gin.Default()

	router.LoadHTMLGlob("views/*")

	router.Use(func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Authorization, Accept, X-Requested-With")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE")
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(200)
			return
		}
		c.Next()
	})

	router.Any("/webhook/:id", func(c *gin.Context) {

		myflow := flow.New()

		jsonByte, _ := utils.ReadFile("task1.json", "tasks")

		data := types.H{"@this": string(jsonByte)}

		data.Get("nodes").ForEach(func(key, value gjson.Result) bool {
			myflow.AddNode(node.New(types.H{"@this": value.String()}))
			return true
		})

		myflow.Debug(func(v ...interface{}) {
			fmt.Println(v...)
		}).Trigger(func(v ...interface{}) {
			c.String(http.StatusOK, utils.ToString(v[0]))
		}).(*flow.FlowStruct).Start(utils.GetPlayload(c)).End()

	})

	manners.ListenAndServe(":6060", router)
}
